<template>
    <div>
        <el-form class="form-box" ref="formRef" :model="form" label-width="auto" size="large">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="收款金额：" prop="salaAmt">
                        <div class="salaAmt">{{ unpay }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="收取现金：" prop="payAmt">
                        <el-input v-model="form.payAmt" placeholder="请输入金额" @focus="focusForm('payAmt')" @blur="blurForm"
                            clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                        <div class="backAmt-box">
                            <!-- giveChange -->
                            <div style="float: right;">找零金额：<span class="color-FF3333">{{ giveChange }}元</span></div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label=" " prop="">
                        <el-row>
                            <el-col :span="7" style="display: flex;">
                                <el-checkbox v-model="form.isGiveAct" true-value="1" false-value="0" size="large" />
                                <div class="isGiveAct">不找赎：</div>
                            </el-col>
                            <el-col :span="17">
                                <el-input v-model="form.notGiveChange" placeholder="输入金额"
                                    @focus="focusForm('notGiveChange')"  @blur="blurForm('notGiveChange')" clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                            </el-col>
                        </el-row>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup >
import ls from '@/lib/ls'
import { formatDecimal } from '@/utils/chenhao'
import Api from '@/api'
import { getLocalIPv4 } from "@/utils/getip.js";
import useConfigStore from '@/store/config'
const configStore = useConfigStore()
const router = useRouter()
// 接收父组件参数 props
const props = defineProps({
    tableInfo: {
        type: Object,
        required: false,
    },
    selectWares: {
        type: Array,
        required: false,
    },
    received: {
        type: String,
        required: false,
    },
    form: {
        type: Object,
        required: false,
    },
    price: {
        type: String,
        required: false,
    },
    unpay: {
        type: String,
        required: false,
    },
    payData: {
        type: Array,
        required: false,
    },
    saleData: {
        type: Array,
        required: false,
    },
    details: {
        type: Array,
        required: false,
    },
})
const tableInfo = toRef(props, 'tableInfo')
const selectWares = toRef(props, 'selectWares')
const received = toRef(props, 'received')
const price = toRef(props, 'price')
const unpay = toRef(props, 'unpay')
const form = toRef(props, 'form')
const payData = toRef(props, 'payData')
const saleData = toRef(props, 'saleData')
const details = toRef(props, 'details')
const emit = defineEmits(['focusForm'])
// 数字键盘
const focusForm = (str) => {
    // keyboard.value = true
    emit('focusForm', str)
}
const blurForm = (params) => {
    switch (params) {
        case 'notGiveChange':
            if(form.value.notGiveChange >= (-(unpay.value - form.value.payAmt))){
                form.value.notGiveChange = formatDecimal(-(unpay.value - form.value.payAmt))
            }
            break;
    
       
    }
   
    // keyboard.value = false
}

const todo = router.currentRoute.value.query.todo
const cardNo = router.currentRoute.value.query.cardNo

// 改变金额计算找零金额
// --------------------------------------------计算属性---------------------------------------
// ----------------计算找零金额------------------
const giveChange = computed(() => {
    if (!form.value.payAmt) return
    // 是否不找赎
    if(form.value.isGiveAct == '1'){
        return formatDecimal(-(Number(unpay.value) - Number(form.value.payAmt) + Number(form.value.notGiveChange))) > 0 ? formatDecimal(-(Number(unpay.value) - Number(form.value.payAmt) + Number(form.value.notGiveChange))) : ''
    }else{
        return formatDecimal(-(unpay.value - form.value.payAmt)) > 0 ? formatDecimal(-(unpay.value - form.value.payAmt)) : ''
    }
    
})

// 父组件小键盘点击确定
const handleKeyboardConfirm = (params) => {
    if (unpay.value <= 0) return ElNotification({
        title: '提示',
        message: '收款金额为0无法收款',
        type: 'warning',
    })
    if (!form.value.payAmt) return ElNotification({
        title: '提示',
        message: '请输入收取金额',
        type: 'warning',
    })
    // if (form.value.notGiveChange > giveChange.value) return ElNotification({
    //     title: '提示',
    //     message: '不找赎金额不能大于找零金额',
    //     type: 'warning',
    // })
    configStore.payFlag = true // 支付开关
    // 换菜
    if (todo == 'orderChange') {
        orderChange()
    }
    // 会员升级
    else if (todo == 'vipUpgrade') {
        vipUpgrade()
    }
    // 挂账还款
    else if (todo == 'mountPay') {
        mountPay()
    }
}

// 换菜支付
const orderChange = (params) => {
    // 处理勾选的商品
    let detailList = []
    if (details.value.length > 0) {
        detailList = details.value
    } else {
         console.log(selectWares.value);
        let toolArr = []
        selectWares.value.forEach(item=>{
            toolArr.push(item)
            if (item.subGoods && item.subGoods.length > 0) {
                toolArr.push(...item.subGoods)
            }
        })
   
        console.log(toolArr);
        
        detailList = toolArr.map(item => {
            return item.itemCode
        })
    }
    const obj = {
        zffs: form.value.actionType,
        skje: giveChange.value > 0 ? unpay.value : formatDecimal(form.value.payAmt),
        consumeCode: form.value.consumeCode,
        payType: '001',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        giveChange: giveChange.value,
        isGiveAct: form.value.isGiveAct,
        notGiveChange: form.value.isGiveAct == '1' ? form.value.notGiveChange : 0,
        detailList,
    }
    const data = {
        payType: '001',
        consumeCode: tableInfo.value.consumeCode,
        roomCode: tableInfo.value.roomCode,
        payBatchCode: tableInfo.value.payBatchCode,
        orderAmt: price.value,
        realPayAmt: form.value.payAmt,
        detailList: detailList.join(','),
        payList: [obj],
        serviceAmt: saleData.value
    }
    Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "orgCode": "0004", "contentData": data })
        .then(res => {
            configStore.ispaying.id ++
            console.log('买单确认res :>> ', res);
            obj.itemCode = res.itemCode
            obj.payBatchCode = res.payBatchCode
            tableInfo.value.payBatchCode = res.payBatchCode
            payData.value.push(obj)
            const ls_orderChange = ls.get('orderChange')
            if (ls_orderChange) {
                ls_orderChange.payData = payData.value
                ls.set('orderChange', ls_orderChange)
            }
            form.value.payAmt = ''
            form.value.giveChange = ''
            form.value.notGiveChange = ''
            form.value.isGiveAct = '0'
        })
}

// 会员升级
const vipUpgrade = (params) => {
    const obj = {
        zffs: form.value.actionType,
        skje: giveChange.value > 0 ? unpay.value : formatDecimal(form.value.payAmt),
        payType: '001',
        payAmt: form.value.payAmt,
        giveChange: giveChange.value,
        isGiveAct: form.value.isGiveAct,
        notGiveChange: form.value.isGiveAct == '1' ? form.value.notGiveChange : 0,
    }
    const data = {
        payType: '001',
        tee: form.value.payAmt,
        tradeNo: null,
        cardNo: cardNo,
    }
    // console.log('会员升级支付确认 data :>> ', data);
    Api.Common.PcObjProcess.Do({ "functionName": "MemberUpPay", "contentData": data })
        .then(res => {
            configStore.ispaying.id ++
            console.log('会员升级支付确认 res :>> ', res);
            obj.itemCode = res.itemCode
            payData.value.push(obj)
            form.value.payAmt = ''
            form.value.giveChange = ''
            form.value.notGiveChange = ''
            form.value.isGiveAct = '0'
        })
        .catch(err=>{
            configStore.ispaying.id ++
        })
}

//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });

// 挂账还款
const mountPay = (params) => {
    // console.log('挂账还款支付确认 data :>> ', router.currentRoute.value.query);
    const { consumeCode, payBatchCode, roomCode, payItemCode } = router.currentRoute.value.query
    const obj = {
        zffs: form.value.actionType,
        skje: giveChange.value > 0 ? unpay.value : formatDecimal(form.value.payAmt),
        consumeCode,
        payType: '001',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        giveChange: giveChange.value,
        isGiveAct: form.value.isGiveAct,
        notGiveChange: form.value.isGiveAct == '1' ? form.value.notGiveChange : 0,
    }
    const data = {
        payType: '001',
        payItemCode,
        consumeCode,
        roomCode,
        payBatchCode,
        payAmt: form.value.payAmt,
        // payList: [obj],
        serviceAmt: saleData.value,
        ip:ip.value
    }
    // return
    console.log('挂账还款接口调用前的 data :>> ', data);
    Api.Common.PcObjProcess.Do({ "functionName": "MountPay", "contentData": data })
        .then(res => {
            configStore.ispaying.id ++
            console.log('挂账还款 res :>> ', res);
            obj.itemCode = res.itemCode
            payData.value.push(obj)
            form.value.payAmt = ''
            form.value.authCode = ''
        })
}

// 暴露方法给父组件
defineExpose({ handleKeyboardConfirm })

</script>

<style scoped lang="scss">
.form-box {
    margin-top: 20px;

    ::v-deep {
        .el-input__wrapper {
            background: #F9F9F9;
            border-radius: 8px;
            border: 0;
            font-size: 16px;
            color: #999999;
        }
    }

    .salaAmt {
        font-weight: 400;
        font-size: 16px;
        color: #FF3333;
    }

}

.backAmt-box {
    width: 100%;
    font-size: 13px;
    color: #212121;
}

.color-FF3333 {
    color: #FF3333;
}

.isGiveAct {
    margin-left: 5px;
}
</style>
